﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Configuration;
using App.Core.Service.Vendor;
using App.Core.Entities.Vendor;
using App.Core.Infrastructure;
using App.Core.Infrastructure.Extensions;
using App.Dto.Dtos.Vendor;
using App.Web.Filter;
using AutoMapper;

namespace App.Web.Controllerr
{
    [System.Web.Http.Authorize]
    [System.Web.Http.RoutePrefix("api/Vendor")]
    public class VendorController : ApiController
    {
        #region 属性

        readonly IVendorService iVendorService;
        readonly IVendorAttachfileService iVendorAttachfileService;
        readonly IConsultantService iConsultantService;
        readonly IConsultantAttachfileService iConsultantAttachfileService;

        #endregion

        #region 构造函数
        public VendorController(IVendorService vendorService,
            IVendorAttachfileService vendorAttachfileService,
            IConsultantService iConsultantService,
            IConsultantAttachfileService iConsultantAttachfileService)
        {
            this.iVendorService = vendorService;
            this.iVendorAttachfileService = vendorAttachfileService;
            this.iConsultantService = iConsultantService;
            this.iConsultantAttachfileService = iConsultantAttachfileService;
        }
        #endregion 

        #region 供应商  
        [AuthorizeForWebApi(Auths= "Vendor=View")]
        [ActionName("GetVendor")]
        [HttpGet]
        public async Task<IHttpActionResult> GetVendor(int id)
        {
            VendorEntity entity = await this.iVendorService.FirstOrDefaultAsync(x => x.Id == id);
            IList<VendorAttachfileDto> attachfileVmodels = new List<VendorAttachfileDto>();

            VendorDto vmodel = new VendorDto();
            Mapper.Map(entity,vmodel);

            if (entity.Attachfiles != null && entity.Attachfiles.Count > 0)
            {
                Mapper.Map(entity.Attachfiles.ToList(),attachfileVmodels);
            }

            return Ok(new { IsAccess = true,Model = vmodel,AttachfileList = attachfileVmodels });
        }

        [AuthorizeForWebApi(Auths = "Vendor=View")]
        [ActionName("GetVendorList")]
        [HttpGet]
        public async Task<IHttpActionResult> GetVendorList(string vendorName = "", string combination = "", int pageIndex = 1, int pageSize = 10)
        {  
            Expression<Func<VendorEntity, bool>> where = x =>
             (String.IsNullOrEmpty(vendorName) || x.CompanyName.Contains(vendorName))
             && (String.IsNullOrEmpty(combination) || x.Combination.Contains(combination));

            Expression<Func<VendorEntity, DateTime>> orderBy = x => x.UpdatedDate;

            int total = await  this.iVendorService.CountAsync(where);
            IList<VendorEntity> entities = await this.iVendorService.GetByPagerAsync(where, orderBy,pageIndex,pageSize,true);

            IList<VendorDto> vmodel = new List<VendorDto>();
            Mapper.Map(entities, vmodel);

            return Ok(new { total = total,pageindex = pageIndex,pagesize =  pageSize,list = vmodel });
        }

        [AuthorizeForWebApi(Auths = "Vendor=Edit")]
        [ActionName("VendorEdit")]
        [HttpPost]
        public IHttpActionResult VendorEdit([FromBody]VendorDto vmodel)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new { IsAccess = false, Tag = "FormFeildIncomplete" });
            }

            if (vmodel.Id > 0)
            {
                var entity = this.iVendorService.FirstOrDefault(x => x.Id == vmodel.Id);
                Mapper.Map(vmodel, entity);
                this.iVendorService.Edit(entity,vmodel.AttachfileId);
            }
            else
            {
                var entity = new VendorEntity();
                Mapper.Map(vmodel, entity);
                this.iVendorService.Create(entity, vmodel.AttachfileId);
            }

            return Ok(new { IsAccess = true });
        } 
        #endregion

        #region 供应商附件 
        [ActionName("UploadVendorAttachfile")]
        [HttpPost]
        public async Task<IHttpActionResult> UploadVendorAttachfile()
        {
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            string fileSavePath = Config.GetUploadFilePath(); 
            var model = new VendorAttachfileEntity();

            foreach (var item in provider.Contents)
            {
                string fileName = item.Headers.ContentDisposition.FileName; 
                if (!String.IsNullOrEmpty(fileName))
                {
                    fileName = fileName.TrimStart('\"').TrimEnd('\"');
                    Stream stream = item.ReadAsStreamAsync().Result;
                    if (stream.Length <= 0)
                        continue;
                    using (var binaryReader = new BinaryReader(stream))
                    {
                        byte[] fileBytes = binaryReader.ReadBytes((int)stream.Length);
                        model.FileName = fileName;
                        model.FileSavedPath = fileSavePath + "\\" + Guid.NewGuid().ToString() + Path.GetExtension(fileName);
                        model.FileSize = ((int) stream.Length / 1024).AsNumericStr(); 
                        File.WriteAllBytes(model.FileSavedPath,fileBytes);
                        model = this.iVendorAttachfileService.Add(model);
                    }
                    break;
                }
            }

            if (model.Id == 0)
                return Ok();

            var dto = new VendorAttachfileDto();
            Mapper.Map(model, dto);

            return Ok(new { File = dto });
        }

        #endregion

        #region 顾问

        [ActionName("GetConsultant")]
        [HttpGet]
        public async Task<IHttpActionResult> GetConsultant(int id)
        {
            ConsultantEntity entity = await this.iConsultantService.FirstOrDefaultAsync(x => x.Id == id);
            IList<ConsultantAttachfileDto> attachfileVmodels = new List<ConsultantAttachfileDto>();

            var vmodel = new ConsultantDto();
            Mapper.Map(entity, vmodel);

            if (entity.Attachfiles != null && entity.Attachfiles.Count > 0)
            {
                Mapper.Map(entity.Attachfiles.ToList(), attachfileVmodels);
            }

            return Ok(new { IsAccess = true, Model = vmodel, AttachfileList = attachfileVmodels });
        }

        [ActionName("GetConsultantList")]
        [HttpGet]
        public async Task<IHttpActionResult> GetConsultantList(string vendorName = "", string name = "", int pageIndex = 1, int pageSize = 10)
        {
            Expression<Func<ConsultantEntity, bool>> where = x =>
             (String.IsNullOrEmpty(vendorName) || x.Vendor.CompanyName.Contains(vendorName))
             && (String.IsNullOrEmpty(name) || x.Name.Contains(name));

            Expression<Func<ConsultantEntity, DateTime>> orderBy = x => x.UpdatedDate;

            int total = await this.iConsultantService.CountAsync(where);
            IList<ConsultantEntity> entities = await this.iConsultantService.GetByPagerAsync(where, orderBy, pageIndex, pageSize, true);

            IList<ConsultantDto> vmodel = new List<ConsultantDto>();
            Mapper.Map(entities, vmodel);

            return Ok(new { total = total, pageindex = pageIndex, pagesize = pageSize, list = vmodel });
        }

        public IHttpActionResult ConsultantEdit([FromBody]ConsultantDto vmodel)
        {
            if (!ModelState.IsValid)
            {
                return Ok(new { IsAccess = false, Tag = "FormFeildIncomplete" });
            }

            if (vmodel.Id > 0)
            {
                var entity = this.iConsultantService.FirstOrDefault(x => x.Id == vmodel.Id);
                Mapper.Map(vmodel, entity);
                this.iConsultantService.Edit(entity, vmodel.AttachfileId);
            }
            else
            {
                var entity = new ConsultantEntity();
                Mapper.Map(vmodel, entity);
                entity.Vendor = null;
                this.iConsultantService.Create(entity, vmodel.AttachfileId);
            }

            return Ok(new { IsAccess = true });
        }

        #endregion

        #region 顾问附件
        [ActionName("UploadConsultantAttachfile")]
        [HttpPost]
        public async Task<IHttpActionResult> UploadConsultantAttachfile()
        {
            var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

            string fileSavePath = Config.GetUploadFilePath();
            var model = new ConsultantAttachfileEntity();

            foreach (var item in provider.Contents)
            {
                string fileName = item.Headers.ContentDisposition.FileName;
                if (!String.IsNullOrEmpty(fileName))
                {
                    fileName = fileName.TrimStart('\"').TrimEnd('\"');
                    Stream stream = item.ReadAsStreamAsync().Result;
                    if (stream.Length <= 0)
                        continue;
                    using (var binaryReader = new BinaryReader(stream))
                    {
                        byte[] fileBytes = binaryReader.ReadBytes((int) stream.Length);
                        model.FileName = fileName;
                        model.FileSavedPath = fileSavePath + "\\" + Guid.NewGuid().ToString() + Path.GetExtension(fileName);
                        model.FileSize = ((int) stream.Length / 1024).AsNumericStr();
                        File.WriteAllBytes(model.FileSavedPath, fileBytes);
                        model = this.iConsultantAttachfileService.Add(model);
                    }
                    break;
                }
            }

            if (model.Id == 0)
                return Ok();

            var dto = new ConsultantAttachfileDto();
            Mapper.Map(model, dto);

            return Ok(new { File = dto });
        }

        #endregion
    } 
}
